package com.yupi.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //重点用户
    private List<Long> mainUserList= Arrays.asList(1L);

    //每天执行，预热推荐用户
    @Scheduled(cron="0 27 15 * * *") //自己设置时间测试
    public void doCacheRecommendUser(){
//        //查数据库
//        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
//        //从数据库中获取第一页的前20个用户作为推荐用户数据，并将结果存储在Page<User>类型的变量userPage中
//        Page<User> userPage=userService.page(new Page<>(1,20),queryWrapper);
//        //构造Redis缓存键名，这里采用字符串格式化的方式
//        String redisKey=String.format("shayu:user:recommend:%s",mainUserList);
//        //redisTemplate中获取ValueOperations实例，用于对Redis值进行操作
//        ValueOperations valueOperations= redisTemplate.opsForValue();
//        //写缓存，30s过期
//        try{
//            //将查询到的推荐用户数据userPage写入Redis缓存，并设置30秒的过期时间
//            valueOperations.set(redisKey,userPage,3000, TimeUnit.MILLISECONDS);
//        } catch (Exception e){
//            log.error("redis set key error",e);
//        }

        RLock lock=redissonClient.getLock("shayu:precachejob:docache:lock");

        try {
            //只有一个线程能获取到锁
            if (lock.tryLock(0,-1,TimeUnit.MILLISECONDS)){
                System.out.println("getLock: "+Thread.currentThread().getId());
                for (Long userId:mainUserList){
                    //查询数据库
                    QueryWrapper<User> queryWrapper=new QueryWrapper<>();
                    Page<User> userPage=userService.page(new Page<>(1,20),queryWrapper);
                    String redisKey=String.format("shayu:user:recommend:%s",mainUserList);
                    // 从 RedisTemplate 获取 ValueOperations 实例
                    ValueOperations valueOperations= redisTemplate.opsForValue();
                    //写缓存30S过期
                    try{
                        valueOperations.set(redisKey,userPage,30000,TimeUnit.MILLISECONDS);
                    } catch (Exception e){
                        log.error("redis set key error",e);
                    }
                }
            }
        } catch (InterruptedException e){
            log.error("doCacheRecommendUser error",e);
        } finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()){
                System.out.println("unLock: "+Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }
}
